package cn.edu.hrbcu.es.invigilatemanagerment.service;

import cn.edu.hrbcu.es.invigilatemanagerment.dao.ExaminfoMapper;
import cn.edu.hrbcu.es.invigilatemanagerment.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ExamInfoServiceImpl implements IExamInfoService{
    @Autowired
    private ExaminfoMapper examinfoMapper;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private IClazzService clazzService;
    @Autowired
    private  ITeacherService teacherService;
    @Override
    public List<Examinfo> queryAllExamInfo() {
        ExaminfoExample example = new ExaminfoExample();
        ExaminfoExample.Criteria criteria = example.createCriteria();
        criteria.andIdGreaterThan(0);
        return examinfoMapper.selectByExample(example);
    }

    @Override
    public List<Examinfo> queryAllExamInfoByClazzId(Integer id) {
        ExaminfoExample example = new ExaminfoExample();
        ExaminfoExample.Criteria criteria = example.createCriteria();
        criteria.andClazzIdEqualTo(id);
        return examinfoMapper.selectByExample(example);
    }

    @Override
    public Examinfo queryExamInfoById(Integer id) {
        return examinfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer insertExamInfo(Examinfo examinfo) {
        return examinfoMapper.insert(examinfo);
    }

    @Override
    public Integer updateExamInfoById(Examinfo examinfo) {
        return examinfoMapper.updateByPrimaryKey(examinfo);
    }

    @Override
    public Integer deleteExamInfoById(Integer id) {
        return examinfoMapper.deleteByPrimaryKey(id);
    }

//    导出
    @Override
    public void exportExcel() {
//        创建一个工作薄
        Workbook workbook = new SXSSFWorkbook();
//        创建一个表
        Sheet sheet = workbook.createSheet();
        List<Examinfo> examinfos = queryAllExamInfo();
//        创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("id");
        headerRow.createCell(1).setCellValue("课程名称");
        headerRow.createCell(2).setCellValue("班级名称");
        headerRow.createCell(3).setCellValue("教师名称");
        headerRow.createCell(4).setCellValue("学生人数");
        headerRow.createCell(5).setCellValue("考试教室");
        headerRow.createCell(6).setCellValue("考试日期");
        headerRow.createCell(7).setCellValue("开考时间");
        headerRow.createCell(8).setCellValue("结束时间");
        headerRow.createCell(9).setCellValue("备注");

        // 创建日期和时间格式
        CreationHelper creationHelper = workbook.getCreationHelper();
        CellStyle dateStyle = workbook.createCellStyle();
        dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd"));
        CellStyle timeStyle = workbook.createCellStyle();
        timeStyle.setDataFormat(creationHelper.createDataFormat().getFormat("HH:mm:ss"));

        // 日期和时间格式化
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

//        创建行
        int rownum = 1;
        for(Examinfo examinfo:examinfos)
        {
            Row row = sheet.createRow(rownum++);

            Integer id = examinfo.getId();
            row.createCell(0).setCellValue(id);
//            通过课程Id获取课程名
            Integer courseId = examinfo.getCourseId();
            String courseName = courseService.queryCourseById(courseId).getName();

            row.createCell(1).setCellValue(courseName);
//            通过班级Id获取班级名称
            Integer clazzId = examinfo.getClazzId();
            String clazzName = clazzService.queryClazzById(clazzId).getName();
            row.createCell(2).setCellValue(clazzName);
//            通过教师Id获取教师名称
            Integer teacherId = examinfo.getTeacherId();
            String teacherName = teacherService.queryTeacherById(teacherId).getName();
            row.createCell(3).setCellValue(teacherName);

            Integer studentNum = examinfo.getStudentNum();
            row.createCell(4).setCellValue(studentNum);

            String classroom = examinfo.getClassroom();
            row.createCell(5).setCellValue(classroom);

            String day = examinfo.getDay();
            Cell dayCell = row.createCell(6);
            try {
                dayCell.setCellValue(dateFormat.parse(day));
                dayCell.setCellStyle(dateStyle);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            String beginTime = examinfo.getBeginTime();
            Cell beginTimeCell = row.createCell(7);
            try {
                beginTimeCell.setCellValue(timeFormat.parse(beginTime));
                beginTimeCell.setCellStyle(timeStyle);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            String endTime = examinfo.getEndTime();
            Cell endTiemCell = row.createCell(8);
            try {
                endTiemCell.setCellValue(timeFormat.parse(endTime));
                endTiemCell.setCellStyle(timeStyle);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            String note = examinfo.getNote();
            row.createCell(9).setCellValue(note);
        }
        String path = "D:/";
        try {
            FileOutputStream fps = new FileOutputStream(path+"考场信息表.xlsx");
            workbook.write(fps);
            ((SXSSFWorkbook) workbook).dispose();
            fps.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

//    导入
    @Override
    public void importExcel(Path path) {
        try {
//            System.out.println(String.valueOf(path));
            FileInputStream fis = new FileInputStream(String.valueOf(path));
            Workbook workbook = new XSSFWorkbook(fis);

            Sheet sheet = workbook.getSheetAt(0);

            int rowcou = sheet.getPhysicalNumberOfRows();
            for(int i=1;i<rowcou;i++)
            {
                Row row = sheet.getRow(i);
                if(row!=null)
                {
                    Examinfo examinfo = new Examinfo();
                    String courseName = row.getCell(1).getStringCellValue();
                    List<Course> courses = courseService.queryCourseByName(courseName);
                    if(!courses.isEmpty()) {
                        Integer courseId = courses.get(0).getId();
                        examinfo.setCourseId(courseId);
                    }

                    String clazzName = row.getCell(2).getStringCellValue();
                    List<Clazz> clazzes = clazzService.queryClazzByName(clazzName);
                    if(!clazzes.isEmpty())
                    {
                        Integer clazzId = clazzes.get(0).getId();
                        examinfo.setClazzId(clazzId);
                    }

                    String teacherName = row.getCell(3).getStringCellValue();
                    List<Teacher> teachers = teacherService.queryTeacherByName(teacherName);
                    if(!teachers.isEmpty())
                    {
                        Integer teacherId = teachers.get(0).getId();
                        examinfo.setTeacherId(teacherId);
                    }

                    Integer studentNum = (int) row.getCell(4).getNumericCellValue();
                    examinfo.setStudentNum(studentNum);

                    String classroom = row.getCell(5).getStringCellValue();
                    examinfo.setClassroom(classroom);

                    Cell dayCell = row.getCell(6);
                    if(DateUtil.isCellDateFormatted(dayCell))
                    {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String day = dateFormat.format(dayCell.getDateCellValue());
                        examinfo.setDay(day);
                    }

                    Cell beginTimeCell = row.getCell(7);
                    if(DateUtil.isCellDateFormatted(beginTimeCell))
                    {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
                        String beginTime = dateFormat.format(beginTimeCell.getDateCellValue());
                        examinfo.setBeginTime(beginTime);
                    }

                    Cell endTimeCell = row.getCell(8);
                    if(DateUtil.isCellDateFormatted(endTimeCell))
                    {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
                        String endTime = dateFormat.format(endTimeCell.getDateCellValue());
                        examinfo.setEndTime(endTime);
                    }

                    String note = row.getCell(9).getStringCellValue();
                    examinfo.setNote(note);

                    insertExamInfo(examinfo);
                }
            }

            workbook.close();
            fis.close();

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int queryExamInfoCount() {
        ExaminfoExample example = new ExaminfoExample();
        ExaminfoExample.Criteria criteria = example.createCriteria();
        criteria.getAllCriteria();
        return (int) examinfoMapper.countByExample(example);
    }

    @Override
    public List<Examinfo> queryExamInfoByPage(int pageNow,int pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Examinfo> examinfos = this.queryAllExamInfo();
        PageInfo<Examinfo> examinfoPageInfo = new PageInfo<>(examinfos);
        return examinfoPageInfo.getList();
    }
}
